package com.geotmt.billingcenter.modules.consume.controller;

import com.alibaba.druid.util.StringUtils;
import com.geotmt.billingcenter.common.exception.MyException;
import com.geotmt.billingcenter.common.result.ResponseResult;
import com.geotmt.billingcenter.common.vo.consume.ConsumeHisVo;
import com.geotmt.billingcenter.common.vo.consume.ConsumeVo;
import com.geotmt.billingcenter.common.vo.params.PageOrgFilter;
import com.geotmt.billingcenter.common.vo.params.ParamsConsume;
import com.geotmt.billingcenter.common.vo.params.ParamsForDel;
import com.geotmt.billingcenter.config.kafka.KafkaSender;
import com.geotmt.billingcenter.modules.consume.service.ConsumeService;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @Description 消耗类 Controller
 * @Author      yanghanwei
 * @Mail        yanghanwei@geotmt.com
 * @Date        2019/3/13 11:36
 * @Version     v1
 **/
@RestController
@RequestMapping(value = "/bc/consume")
@Api(value = "消耗配置接口",tags = "消耗配置接口")
public class ConsumeController extends PageOrgFilter {

    private static final Logger logger = LoggerFactory.getLogger(ConsumeController.class);

    @Resource
    private ConsumeService consumeService;

    @Resource
    private KafkaSender kafkaSender;

    @Resource
    private RedisTemplate redisTemplate;

    /**
     * 测试kafak
     * @param mag
     * @return
     */
    @ApiOperation(value = "测试kafak,redis")
    @RequestMapping(value = "/test", method = RequestMethod.GET)
    public String teste(@RequestParam(value = "msg") String mag){

//        kafkaSender.send("test121", mag);
//        redisTemplate.opsForValue().set("name",mag);
        System.out.println(redisTemplate.opsForValue().get("name"));
        return "success";
    }


    /**
     * 添加规则配置
     * @return
     */
    @ApiOperation(value = "ADD CURR 配置（批量）")
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public ResponseResult addConsume(@RequestBody List<ConsumeVo> consumeVoList, HttpServletRequest request){
        logger.info("添加规则配置,consumeVoList:{}",consumeVoList);
        try{
            if(null != consumeVoList && !consumeVoList.isEmpty()){
                for(ConsumeVo consumeVo : consumeVoList){
                    if(StringUtils.isEmpty(consumeVo.getProductCode()) || null == consumeVo.getCompanyId() || null == consumeVo.getCuserId()
                            || null == consumeVo.getInterfaceId() || null == consumeVo.getLabel() || null == consumeVo.getFeeFlag()){
                        return ResponseResult.build(HttpServletResponse.SC_NOT_ACCEPTABLE,"产品code,客户，用户，接口,接口类别，计费模式 不能为空",null,false);
                    }
                    consumeVo.setCreateUserId(getUserId(request));
                    consumeVo.setCreateTime(new Date());
                }
            }
            consumeService.addList(consumeVoList);
        }catch (MyException e){
            logger.error("添加最新规则失败");
            return ResponseResult.build(e.getCode(),e.getMsg(),null,false);
        }catch (Exception e) {
            logger.error("添加最新规则失败",e);
            return ResponseResult.error("添加失败");
        }
        return ResponseResult.ok("添加成功");
    }


    /**
     * 批量添加修改规则配置
     * @return
     */
    @ApiOperation(value = "ADD/UPDATE  规则配置（批量）")
    @RequestMapping(value = "/addUpdateConsumeList", method = RequestMethod.POST)
    public ResponseResult addUpdateConsume(@RequestBody List<ConsumeVo> consumeVoList, HttpServletRequest request){
        logger.info("批量添加修改规则配置,consumeVoList:{}",consumeVoList);
        try{
            consumeService.addUpdateList(consumeVoList, request);
        }catch (MyException e){
            logger.error("批量添加修改规则配置失败");
            return ResponseResult.build(e.getCode(),e.getMsg(),null,false);
        }catch (Exception e) {
            e.printStackTrace();
            logger.error("批量添加修改规则配置失败");
            return ResponseResult.error("批量添加修改规则配置失败");
        }
        return ResponseResult.ok("批量添加修改规则配置成功");
    }

    /**
     * 分析List规则配置
     * @return
     */
    @ApiOperation(value = "分析List规则配置")
    @RequestMapping(value = "/analyzeConsumeList", method = RequestMethod.POST)
    public ResponseResult analyzeConsumeList(@RequestBody List<ConsumeVo> consumeVoList){
        logger.info("分析List规则配置,consumeVoList:{}",consumeVoList);
        Map<String, Object> resultMap;
        try{
            resultMap = consumeService.analyzeList(consumeVoList);
        } catch (Exception e) {
            logger.error("分析List规则配置失败",e);
            return ResponseResult.error("分析List规则配置失败");
        }
        return ResponseResult.build(HttpServletResponse.SC_OK,"分析List规则配置成功",resultMap,true);
    }

    /**
     * 修改规则配置
     * @param consumeVo
     * @return
     */
    @ApiOperation(value = "UPDATE CURR 配置")
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public ResponseResult updateConsume(@RequestBody ConsumeVo consumeVo, HttpServletRequest request){
        logger.info("修改规则配置,consumeVo:{}",consumeVo);
        try{
            if(null == consumeVo.getId()){
                return ResponseResult.build(HttpServletResponse.SC_NOT_ACCEPTABLE,"id不能为空",null,false);
            }
            consumeVo.setUpdateTime(new Date());
            consumeVo.setUpdateUserId(getUserId(request));
            consumeService.update(consumeVo);
        }catch (MyException e){
            logger.error("修改最新规则失败");
            return ResponseResult.build(e.getCode(),e.getMsg(),null,false);
        }catch (Exception e) {
            logger.error("修改最新规则失败",e);
            return ResponseResult.error("修改失败");
        }
        return ResponseResult.ok("修改成功");
    }

    /**
     * 删除
     * @param obj
     * @return
     */
    @ApiOperation(value = "DELETE CURR 配置")
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public ResponseResult deleteConsume(@RequestBody ParamsForDel obj, HttpServletRequest request){
        logger.info("删除规则配置,obj:{}",obj);
        try{
            if(null == obj.getId()){
                return ResponseResult.build(HttpServletResponse.SC_NOT_ACCEPTABLE,"id不能为空",null,false);
            }
            obj.setUpdateUserId(getUserId(request));
            obj.setUpdateTime(new Date());
            consumeService.delete(obj);
        }catch (MyException e){
            logger.error("删除最新规则失败");
            return ResponseResult.build(e.getCode(),e.getMsg(),null,false);
        }catch (Exception e) {
            logger.error("删除最新规则失败",e);
            return ResponseResult.error("删除失败");
        }
        return ResponseResult.ok("删除成功");
    }

    /**
     * 历史规则的覆盖修改
     * @param obj
     * @return
     */
    @ApiOperation(value = "历史规则的覆盖修改 ??")
    @RequestMapping(value = "/updateHis", method = RequestMethod.POST)
    public ResponseResult updateHis(@RequestBody ConsumeHisVo obj, HttpServletRequest request){
        logger.info("历史消耗规则 覆盖修改,ConsumeHisVo:{}",obj);
        try{
            obj.setUpdateUserId(getUserId(request));
            obj.setCreateTime(new Date());
            consumeService.updateHis(obj);
        }catch (MyException e){
            logger.error("覆盖修改失败");
            return ResponseResult.build(e.getCode(),e.getMsg(),null,false);
        }catch (Exception e) {
            logger.error("历史消耗规则 覆盖修改",e);
            return ResponseResult.error("覆盖修改失败");
        }
        return ResponseResult.ok("覆盖修改成功");
    }

    /**
     * 最新规则List
     * @param obj
     * @return
     */
    @ApiOperation(value = "CURR List")
    @RequestMapping(value = "/listCurr", method = RequestMethod.POST)
    public ResponseResult listCurr(@RequestBody ParamsConsume obj){
        logger.info("最新规则 list,ParamsConsume:{}",obj);
        filterPage(obj,"curr.id desc");
        PageInfo<ConsumeVo> pageInfo;
        try{
            pageInfo = new PageInfo<>(consumeService.list(obj));
        }catch (Exception e) {
            logger.error("最新规则 list 查询失败",e);
            return ResponseResult.error("查询失败");
        }
        return ResponseResult.build(HttpServletResponse.SC_OK,"查询成功",pageInfo,true);
    }

    /**
     * 添加或修改的回显List
     * @param obj
     * @return
     */
    @ApiOperation(value = "ListAll add/update 回显接口")
    @RequestMapping(value = "/listAllConsume", method = RequestMethod.POST)
    public ResponseResult listAllConsume(@RequestBody ParamsConsume obj){
        logger.info("添加或修改的回显list,ParamsConsume:{}",obj);
        List<ConsumeVo> consumeVos;
        try{
            consumeVos = consumeService.listAll(obj);
        }catch (Exception e) {
            logger.error("添加或修改的回显 list 查询失败",e);
            return ResponseResult.error("添加或修改的回显list查询失败");
        }
        return ResponseResult.build(HttpServletResponse.SC_OK,"添加或修改的回显list查询成功",consumeVos,true);
    }

    /**
     * 历史规则List
     * @param obj
     * @return
     */
    @ApiOperation(value = "HIS List")
    @RequestMapping(value = "/listHis", method = RequestMethod.POST)
    public ResponseResult listHis(@RequestBody ParamsConsume obj){
        logger.info("历史规则 list,ParamsConsume:{}",obj);
        filterPage(obj,"currHis.effect_start_time desc");
        List<ConsumeHisVo> consumeHisVos = null;
        PageInfo<ConsumeHisVo> pageInfo;
        try{
            pageInfo = new PageInfo<>(consumeService.listHis(obj));
        }catch (Exception e) {
            logger.error("历史规则 list 查询失败",e);
            return ResponseResult.error("查询失败");
        }
        return ResponseResult.build(HttpServletResponse.SC_OK,"查询成功",pageInfo,true);
    }

}
